
angular.module('U9ImPDA.services')

.factory('LfRfid', ['$q', '$rootScope', function ($q, $rootScope) {

    document.addEventListener('LFRFID.DataReceived', function (e) {
        $rootScope.$broadcast('LFRFID.DataReceived', parseLfRfidData(e.lfrfidData));
    }, false);

    return {
        open: openRfid,
        close: closeRfid
    };

    function parseLfRfidData (data) {
        if (data.length < 16) {
            return '';
        }
        var result = parseInt(data.substr(8, 8), 16).toString(),
            ct = 10 - result.length,
            zeroStr = '';
        for (var i = 0; i < ct; i++) {
            zeroStr += '0';
        }
        return zeroStr + result;
    }

    function openRfid () {
        var defer = $q.defer();

        if (window.cordova && cordova.plugins.lfrfid) {
            cordova.plugins.lfrfid.open(function () {
                defer.resolve();
            }, function () {
                defer.reject('打开低频LfRfid失败');
            });
        } else {
            defer.reject('请安装低频LfRfid插件');
        }

        return defer.promise;
    }

    function closeRfid () {
        if (window.cordova && cordova.plugins.lfrfid) {
            cordova.plugins.lfrfid.close();
        }
    }
}]);